package com.framework.bdf4j.comm.web;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * js调用 thymeleaf 实现按钮权限可见性
 * 
 */
@Service("permission")
public class PermissionService
{
    /** 没有权限，hidden用于前端隐藏按钮 */
    public static final String NOACCESS = "hidden";

    private static final String ROLE_DELIMETER = ",";

    private static final String PERMISSION_DELIMETER = ",";

    /**
     * 验证用户是否具备某权限，无权限返回hidden用于前端隐藏（如需返回Boolean使用isPermitted）
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public String hasPermi(String permission)
    {
        return isPermitted(permission) ? StringUtils.EMPTY : NOACCESS;
    }

    /**
     * 判断用户是否拥有某个权限
     * 
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public boolean isPermitted(String permission)
    {
        boolean result = false;
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        for(GrantedAuthority grantedAuthority : authorities){
            if (permission.equalsIgnoreCase(grantedAuthority.getAuthority())) {
                result = true;
                break;
          }
        }
        return result;
    }
}
